package com.ruoyi.mushcoin.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryTable;
import com.mybatisflex.core.query.QueryWrapper;
import com.ruoyi.common.core.utils.MapstructUtils;
import com.ruoyi.common.orm.core.page.PageQuery;
import com.ruoyi.common.orm.core.page.TableDataInfo;
import com.ruoyi.common.orm.core.service.impl.BaseServiceImpl;
import com.ruoyi.mushcoin.common.WalletCommon;
import com.ruoyi.mushcoin.domain.TgGameGoodsInfo;
import com.ruoyi.mushcoin.domain.TgUserInfo;
import com.ruoyi.mushcoin.domain.TgWalletOrderTransaction;
import com.ruoyi.mushcoin.domain.bo.TgWalletOrderTransactionBo;
import com.ruoyi.mushcoin.domain.vo.TgWalletOrderTransactionVo;
import com.ruoyi.mushcoin.mapper.TgWalletOrderTransactionMapper;
import com.ruoyi.mushcoin.service.ITgGameGoodsInfoService;
import com.ruoyi.mushcoin.service.ITgUserInfoService;
import com.ruoyi.mushcoin.service.ITgWalletOrderTransactionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.ruoyi.mushcoin.domain.table.TgWalletOrderTransactionTableDef.TG_WALLET_ORDER_TRANSACTION;

/**
 * TG钱包订单交易(Ton...)Service业务层处理
 *
 * @author billy
 * 2024-11-01
 */
@Service
@Slf4j
public class TgWalletOrderTransactionServiceImpl extends BaseServiceImpl<TgWalletOrderTransactionMapper, TgWalletOrderTransaction> implements ITgWalletOrderTransactionService {
    @Resource
    private TgWalletOrderTransactionMapper tgWalletOrderTransactionMapper;

    @Autowired
    private ITgUserInfoService userInfoService;
    @Autowired
    private ITgGameGoodsInfoService goodsInfoService;

    @Override
    public QueryWrapper query() {
        return super.query().from(TG_WALLET_ORDER_TRANSACTION);
    }

    private QueryWrapper buildQueryWrapper(TgWalletOrderTransactionBo tgWalletOrderTransactionBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.ID.eq(tgWalletOrderTransactionBo.getId()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.USER_ID.eq(tgWalletOrderTransactionBo.getUserId()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.GOODS_ID.eq(tgWalletOrderTransactionBo.getGoodsId()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.PAY_ORDER_ID.eq(tgWalletOrderTransactionBo.getPayOrderId()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.AMOUNT_TO.eq(tgWalletOrderTransactionBo.getAmountTo()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.FROM_ADDRESS.eq(tgWalletOrderTransactionBo.getFromAddress()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.TO_ADDRESS.eq(tgWalletOrderTransactionBo.getToAddress()));
        if(tgWalletOrderTransactionBo.getStatus() == null && tgWalletOrderTransactionBo.getId()==null){
            queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.STATUS.gt(0));
        }else{
            queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.STATUS.eq(tgWalletOrderTransactionBo.getStatus()));
        }

        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.WALLET_TYPE.eq(tgWalletOrderTransactionBo.getWalletType()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.COIN_TRANS_PRICE.eq(tgWalletOrderTransactionBo.getCoinTransPrice()));
        queryWrapper.and(TG_WALLET_ORDER_TRANSACTION.TRANS_TYPE.eq(tgWalletOrderTransactionBo.getTransType()));

        return queryWrapper;
    }

    /**
     * 查询TG钱包订单交易(Ton...)
     *
     * @param id TG钱包订单交易(Ton...)主键
     * @return TG钱包订单交易(Ton...)
     */
    @Override
    public TgWalletOrderTransactionVo selectById(Long id) {
        return this.getOneAs(query().where(TG_WALLET_ORDER_TRANSACTION.ID.eq(id)), TgWalletOrderTransactionVo.class);

    }

    /**
     * 查询TG钱包订单交易(Ton...)列表
     *
     * @param tgWalletOrderTransactionBo TG钱包订单交易(Ton...)Bo
     * @return TG钱包订单交易(Ton...)集合
     */
    @Override
    public List<TgWalletOrderTransactionVo> selectList(TgWalletOrderTransactionBo tgWalletOrderTransactionBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(tgWalletOrderTransactionBo);
        return this.listAs(queryWrapper, TgWalletOrderTransactionVo.class);
    }

    /**
     * 分页查询TG钱包订单交易(Ton...)列表
     *
     * @param tgWalletOrderTransactionBo TG钱包订单交易(Ton...)Bo
     * @return 分页TG钱包订单交易(Ton...)集合
     */
    @Override
    public TableDataInfo<TgWalletOrderTransactionVo> selectPage(TgWalletOrderTransactionBo tgWalletOrderTransactionBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(tgWalletOrderTransactionBo);
        queryWrapper.select("t1.id,t1.user_id,t1.goods_id,t1.pay_order_id,t1.transaction_id,t1.amount,t1.amount_to,t1.from_address,t1.to_address,t1.status,t1.wallet_type,t1.coin_trans_price,t1.remark,t1.create_time,t1.update_time,t1.task_vip_end_time,t1.trans_type,t1.transaction_hash"
            , "concat(user.first_name,' ',user.last_name) realName,user.user_name"
            , "t2.address default_address"
            , "t3.title goods_title"
        );
        queryWrapper.from(TgWalletOrderTransaction.class).as("t1");
        queryWrapper.leftJoin(new QueryTable("tg_user_info").as("user")).on("user.user_id=t1.user_id");
        queryWrapper.leftJoin(new QueryTable("tg_user_wallet_address").as("t2")).on("t1.user_id=t2.user_id");
        queryWrapper.leftJoin(new QueryTable("tg_game_goods_info").as("t3")).on("t1.goods_id=t3.goods_id");

        Page<TgWalletOrderTransactionVo> page = this.pageAs(PageQuery.build(), queryWrapper, TgWalletOrderTransactionVo.class);
        return TableDataInfo.build(page);
    }

    /**
     * 新增TG钱包订单交易(Ton...)
     *
     * @param tgWalletOrderTransactionBo TG钱包订单交易(Ton...)Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(TgWalletOrderTransactionBo tgWalletOrderTransactionBo) {
        TgWalletOrderTransaction tgWalletOrderTransaction = MapstructUtils.convert(tgWalletOrderTransactionBo, TgWalletOrderTransaction.class);


        return this.save(tgWalletOrderTransaction);//使用全局配置的雪花算法主键生成器生成ID值
    }

    /**
     * 新增TG钱包订单交易(Ton...)，前台提供主键值，一般用于导入的场合
     *
     * @param tgWalletOrderTransactionBo TG钱包订单交易(Ton...)Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(TgWalletOrderTransactionBo tgWalletOrderTransactionBo) {
        TgWalletOrderTransaction tgWalletOrderTransaction = MapstructUtils.convert(tgWalletOrderTransactionBo, TgWalletOrderTransaction.class);


        return tgWalletOrderTransactionMapper.insertWithPk(tgWalletOrderTransaction) > 0;//前台传来主键值
    }

    /**
     * 修改TG钱包订单交易(Ton...)
     *
     * @param tgWalletOrderTransactionBo TG钱包订单交易(Ton...)Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(TgWalletOrderTransactionBo tgWalletOrderTransactionBo) {
        TgWalletOrderTransaction tgWalletOrderTransaction = MapstructUtils.convert(tgWalletOrderTransactionBo, TgWalletOrderTransaction.class);
        if (ObjectUtil.isNotNull(tgWalletOrderTransaction) && ObjectUtil.isNotNull(tgWalletOrderTransaction.getId())) {
            boolean updated = this.updateById(tgWalletOrderTransaction);
            return updated;
        }
        return false;
    }


    /**
     * 批量删除TG钱包订单交易(Ton...)
     *
     * @param ids 需要删除的TG钱包订单交易(Ton...)主键集合
     * @return 结果:true 删除成功，false 删除失败
     */
    @Transactional
    @Override
    public boolean deleteByIds(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }


    /**
     * 后台修改订单交易成功
     * @param id
     * @return
     */
    public boolean acceptTonOrderTransaction(Long id) {
        Date now=DateUtil.date();
        TgWalletOrderTransaction orderTransaction = this.getById(id);

        if (orderTransaction == null || orderTransaction.getStatus() > 0) {
            log.error("acceptTonOrderTransaction_error: 修改订单支付成功失败，id={}", id);
            return false;
        }

        //交易成功，修改状态
        TgWalletOrderTransaction update = new TgWalletOrderTransaction();
        update.setId(id);
        update.setRemark("""
                        {"transType":1,"result":"system_update_pay_success"}
                        """);
        update.setStatus(3);
        boolean result = this.updateById(update);
        if (result && WalletCommon.GOODS_TYPE_1_VIP.equals(orderTransaction.getGoodsType())) {
            Long goodsId = orderTransaction.getGoodsId();
            TgUserInfo queryUser = userInfoService.getUserInfoByIdEasy(orderTransaction.getUserId());
            TgUserInfo updateUser = new TgUserInfo();
            updateUser.setId(queryUser.getId());
            updateUser.setIsPremium(1);

            if (queryUser.getVipEndTime() == null || queryUser.getVipEndTime().before(now)) {
                updateUser.setVipEndTime(orderTransaction.getTaskVipEndTime());
                userInfoService.updateById(updateUser);
            } else {
                TgGameGoodsInfo goodsInfo = goodsInfoService.getByGoodsId(goodsId);
                Date userVipEndtime = queryUser.getVipEndTime();
                Date vipEndTime = DateUtil.offsetMonth(userVipEndtime, goodsInfo.getGoodsValue().intValue());
                updateUser.setVipEndTime(vipEndTime);
                userInfoService.updateById(updateUser);
            }
        }
        return result;
    }

}
